/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.filters;

import com.bean.Login;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Tuan Long
 */
public class AdminFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession(false);
        Login user = (session != null)? (Login)session.getAttribute("login"):null;
        String url = req.getRequestURI();        
        /*
         1. if request is for index and there's no session, redirect the request to login.xhtml.
         2. if request is for login and there's a session, redirect the request to index.xhtml
         3. if request is for logout and there's a session, remove the session, then redirect to login.xhtml
         */
        if (user == null || !user.isLogged()) {
            boolean b = (url.indexOf("index.xhtml") >= 0) || (url.indexOf("logout.xhtml")>=0)
                        || (url.indexOf("createemployee.xhtml") >= 0) || (url.indexOf("employees.xhtml") >= 0 )
                        || url.indexOf("event.xhtml") >= 0 || url.indexOf("events.xhtml") >= 0
                        || url.indexOf("eventpu.xhtml") >= 0 || url.indexOf("message.xhtml") >= 0
                        || url.indexOf("profile.xhtml") >= 0;
            if (b) {                
                resp.sendRedirect(req.getServletContext().getContextPath() + "/login.xhtml");
            } else {
                chain.doFilter(request, response);
            }
        } else {            
            if(url.indexOf("login.xhtml") >= 0){
                resp.sendRedirect(req.getServletContext().getContextPath() + "/index.xhtml");
            }else if(url.indexOf("logout.xhtml") >=0){
                req.getSession().removeAttribute("login");
                resp.sendRedirect(req.getServletContext().getContextPath() + "/login.xhtml");
            }else{
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {
    }

}
